package com.android.dialer.extendboard;

import android.content.ContentProvider;
import android.content.ContentValues;
import android.content.Context;
import android.content.Intent;
import android.content.SharedPreferences;
import android.database.Cursor;
import android.database.MatrixCursor;
import android.net.Uri;
import android.text.TextUtils;
import android.util.Log;

import com.google.gson.Gson;

import java.util.Arrays;
import java.util.Objects;

public class PhonesContentProvider extends ContentProvider {
    private static final String TAG = "PhonesContentProvider";
    public static final String AUTHORITY = "com.android.dialer.extendboard.provider";
    public static final String BASE_PATH = "phones";
    public static final Uri BASE_CONTENT_URI = Uri.parse("content://" + AUTHORITY);
    public static final Uri CONTENT_URI = BASE_CONTENT_URI.buildUpon().appendPath(BASE_PATH).build();
    public static final String COLUMN_KEY = "key";
    public static final String COLUMN_VALUE = "value";
    private static final String[] PROJECTION = {COLUMN_KEY, COLUMN_VALUE};
    private SharedPreferences sharedPreferences;

    @Override
    public int delete(Uri uri, String selection, String[] selectionArgs) {
        Log.d(TAG, "delete: " + Arrays.toString(selectionArgs));
        if (selectionArgs != null && selectionArgs.length > 0) {
            String key = selectionArgs[0];
            if (sharedPreferences.contains(ServiceConstant.DATA_STORE_KEY_PREFIX + key)) {
                SharedPreferences.Editor editor = sharedPreferences.edit();
                SpeedDialItem item = new SpeedDialItem();
                item.setId(Integer.parseInt(key));
                item.setActive(false);
                editor.putString(ServiceConstant.DATA_STORE_KEY_PREFIX + key, new Gson().toJson(item));
                Log.d(TAG, "delete: key: " + key + ", value: " + item.toString());
                editor.apply();

                Uri newUri = Uri.withAppendedPath(CONTENT_URI, key);
                Log.d(TAG, "delete: newUri: " + newUri.toString());
                Objects.requireNonNull(getContext()).getContentResolver().notifyChange(newUri, null);
                return 1; // Return the number of rows deleted
            }
        }

        return 0; // No rows deleted
    }

    @Override
    public String getType(Uri uri) {
        return "vnd.android.cursor.dir/vnd.com.android.dialer.extendboard.phones";
    }

    @Override
    public Uri insert(Uri uri, ContentValues values) {
        // TODO: Implement this to handle requests to insert a new row.
        throw new UnsupportedOperationException("Not yet implemented");
    }

    @Override
    public boolean onCreate() {
        Log.d(TAG, "onCreate: ------------------------------>");
        Context context = getContext();
        if (context != null) {
            sharedPreferences = context.getSharedPreferences(ServiceConstant.DATA_STORE_NAME, Context.MODE_PRIVATE);

            if (sharedPreferences == null) {
                Log.d(TAG, "onCreate: sharedPreferences is null");
                return false;
            }

            // check whether there are datas in the shared preferences
            if (sharedPreferences.getAll().isEmpty()) {
                SharedPreferences.Editor editor = sharedPreferences.edit();
                for (int i = 0; i < 5; i++) {
                    SpeedDialItem item = new SpeedDialItem();
                    item.setActive(false);
                    item.setId(i + 1);

                    String itemJson = new Gson().toJson(item);
                    Log.d(TAG, "onCreate: itemJson: " + itemJson + "\n" + "item: " + item.toString());
                    editor.putString(ServiceConstant.DATA_STORE_KEY_PREFIX + item.getId(), itemJson);
                }
                editor.apply();
            }

            return true;
        }else {
            Log.d(TAG, "onCreate: context is null");
        }

        return false;
    }

    @Override
    public Cursor query(Uri uri, String[] projection, String selection,
                        String[] selectionArgs, String sortOrder) {
        MatrixCursor cursor = new MatrixCursor(PROJECTION);
        if (selection == null) {
            for (int i = 1; i <= 5; i++) {
                String key = ServiceConstant.DATA_STORE_KEY_PREFIX + i;
                if(sharedPreferences.contains(key)){
                    String value = sharedPreferences.getString(key, null);
                    Log.d(TAG, "query: key: " + key + ", value: " + value);
                    if (value != null) {
                        String keyIndex = key.replace(ServiceConstant.DATA_STORE_KEY_PREFIX, "");
                        cursor.addRow(new Object[]{keyIndex, value});
                    }
                }
            }
        }else {
            String key = selectionArgs != null && selectionArgs.length > 0 ? selectionArgs[0] : null;
            Log.d(TAG, "query: key: " + key);
            if (!TextUtils.isEmpty(key) && sharedPreferences.contains(ServiceConstant.DATA_STORE_KEY_PREFIX + key)) {
                String value = sharedPreferences.getString(ServiceConstant.DATA_STORE_KEY_PREFIX + key, null);
                if (value != null) {
                    cursor.addRow(new Object[]{key, value});
                }
            }
        }

        return cursor;
    }

    @Override
    public int update(Uri uri, ContentValues values, String selection,
                      String[] selectionArgs) {
        Log.d(TAG, "update: " + values.toString());
        if (values != null && values.containsKey(COLUMN_KEY) && values.containsKey(COLUMN_VALUE)) {
            String key = values.getAsString(COLUMN_KEY);
            String value = values.getAsString(COLUMN_VALUE);

            SharedPreferences.Editor editor = sharedPreferences.edit();
            editor.putString(ServiceConstant.DATA_STORE_KEY_PREFIX + key, value);
            Log.d(TAG, "update: key: " + key + ", value: " + value);
            editor.apply();

            Uri newUri = Uri.withAppendedPath(CONTENT_URI, key);
            Log.d(TAG, "update: newUri: " + newUri.toString());
            Objects.requireNonNull(getContext()).getContentResolver().notifyChange(newUri, null);

            return 1; // Return the number of rows updated
        }

        return 0; // No rows updated
    }
}